package cn.t.keycloak.plugin.login.authenticator.conditional;

import org.apache.commons.lang3.StringUtils;
import org.jboss.logging.Logger;
import org.keycloak.authentication.AuthenticationFlowContext;
import org.keycloak.authentication.authenticators.conditional.ConditionalLoaAuthenticator;
import org.keycloak.models.AuthenticatorConfigModel;
import org.keycloak.models.KeycloakSession;

/**
 * @author zhoujw
 * @date 2023/11/29 16:54
 *
 * 校验之前是否是手机验证码登录的
 *  手机验证码登录的会设置一个特殊标志位,根据这个标志位判断
 */
public class ConditionalLoaV3Authenticator extends ConditionalLoaAuthenticator {

    private static final Logger logger = Logger.getLogger(ConditionalLoaV3Authenticator.class);


    // 是否手机验证码登录设置标志位的字段名
    public static final String CUST_ATTR_LOGED_AUTHNOTE_NAME ="custLogedAuthNoteName";
    // 如果是手机验证码登录的，是否跳过后续条件 配置字段
    public static final String CUST_ATTR_LOGED_JUSTPASS_NAME ="passIfPhoneLogin";



    public ConditionalLoaV3Authenticator(KeycloakSession session) {
        super(session);
    }

    @Override
    public boolean matchCondition(AuthenticationFlowContext context) {
        Boolean custAttrLogedNote = this.getCustAttrLogedNote(context);
        if (Boolean.TRUE.equals(custAttrLogedNote)) {
            logger.warn(">>>phone logined .check if can pass.........");
            if (Boolean.TRUE.equals(this.passIfPhoneLogin(context))) {
                logger.info(">>> phone logined and can pass ....");
                return false;
            }else{
                logger.warn(">>> phone logined , but we need continue after conditions.....");
            }
        }

        logger.info(",check level..........");
        return super.matchCondition(context);
    }


    public Boolean getCustAttrLogedNote(AuthenticationFlowContext context){

        AuthenticatorConfigModel authenticatorConfig = context.getAuthenticatorConfig();
        String key = authenticatorConfig.getConfig().get(CUST_ATTR_LOGED_AUTHNOTE_NAME);

        String authNote = context.getAuthenticationSession().getAuthNote(key);
        logger.info("get cust attr logined auth note key:" + key    +". value:" + authNote);
        return StringUtils.equals(authNote,"1");
    }

    public Boolean passIfPhoneLogin(AuthenticationFlowContext context){

        AuthenticatorConfigModel authenticatorConfig = context.getAuthenticatorConfig();
        String ifPass = authenticatorConfig.getConfig().get(CUST_ATTR_LOGED_JUSTPASS_NAME);

        logger.info("get cust attr phone logined if can pass after:" + ifPass );
        return StringUtils.equals(ifPass,"1");
    }
}
